<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Canvas Menu Example</title>
</head>
<body>

<canvas id="canvasMenu" width="800" height="600"></canvas>

<script>
const canvas = document.getElementById('canvasMenu');
const ctx = canvas.getContext('2d');

// Menu data
const menus = [
  { title: '开始', submenu: ['格式', '粘贴'] },
  { title: '插入', submenu: ['表格', '图片', '图标'] },
  { title: '页面布局', submenu: ['页边距', '纸张大小'] }
];

// Positions and sizes
const menuHeight = 30;
const submenuHeight = 60;
const menuItemWidth = 80;
const submenuItemWidth = 120;
const submenuItemHeight = 30;
const submenuX = 10; // X position of the submenu
const submenuY = menuHeight + 5; // Y position of the submenu

// Styles
const menuBgColor = '#ccc';
const submenuBgColor = '#fff';
const submenuHoverColor = '#ccc';
const textColor = '#000';
const textFont = '16px Arial';
const submenuBorderRadius = 5;

// Draw top-level menu
function drawMenu() {
  ctx.fillStyle = menuBgColor;
  ctx.fillRect(0, 0, canvas.width, menuHeight);

  ctx.font = textFont;
  ctx.fillStyle = textColor;

  menus.forEach((menu, index) => {
    const x = index * menuItemWidth;
    ctx.fillText(menu.title, x + 10, menuHeight - 10);
  });
}

// Draw second-level menu
function drawSubmenu(menuIndex) {
  const submenu = menus[menuIndex].submenu;
  ctx.fillStyle = submenuBgColor;
  ctx.fillRect(submenuX, submenuY, submenu.length * submenuItemWidth, submenuHeight);

  ctx.font = textFont;
  ctx.fillStyle = textColor;

  submenu.forEach((item, index) => {
    const x = submenuX + index * submenuItemWidth;
    const y = submenuY + submenuItemHeight / 2;

    // Draw submenu item background
    ctx.fillStyle = submenuBgColor;
    ctx.fillRect(x, submenuY, submenuItemWidth, submenuItemHeight);

    // Set text in the center of submenu item
    const textMeasure = ctx.measureText(item);
    const textX = x + (submenuItemWidth - textMeasure.width) / 2;
    const textY = y + (submenuItemHeight - 16) / 2 + 12;
    ctx.fillStyle = textColor;
    ctx.fillText(item, textX, textY);
  });
}

// Initial draw
drawMenu();

// Event handling
canvas.addEventListener('mousemove', (e) => {
  // Here you would handle mouse movement over the menu items
  // For now, this is just a placeholder function
});

canvas.addEventListener('click', (e) => {
  const rect = canvas.getBoundingClientRect();
  const mouseX = e.clientX - rect.left;
  const mouseY = e.clientY - rect.top;

  // Check if we clicked on a top-level menu
  if (mouseY <= menuHeight) {
    const menuIndex = Math.floor(mouseX / menuItemWidth);
    drawSubmenu(menuIndex);
  }
});

</script>

</body>
</html>
